//
//  SearchViewController.m
//  LastTemp
//
//  Created by apple on 15/4/22.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SearchViewController.h"
#import "AVSingleton.h"
#import "bofangViewController.h"
#import "BassModel.h"

@interface SearchViewController ()
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,retain)UISearchBar *searchBar;
@property(nonatomic,retain)NSMutableArray *arr;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,retain)NSMutableArray *baseArr;
@property(nonatomic,retain)UITextField *back;
@property(nonatomic,retain)UIView *myView;

@end

@implementation SearchViewController


-(void)dealloc
{
    [_arr release];
    [_baseArr release];
    [_back release];
    [_myView release];
    [_tableView release];
    [_searchBar release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nignt"]];
    imageView.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
    

    [self.view addSubview:imageView];
    [imageView release];
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 94, self.view.frame.size.width, self.view.frame.size.height-49) style:UITableViewStylePlain];
    self.tableView.alpha = 0.3;
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 70;
    self.back = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [self.view addSubview:self.back];
    self.back.alpha = 0;
    self.back.delegate = self;
    [_back release];


    
 
//    [self.tableView footerBeginRefreshing];

    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 30)];
    [self.view addSubview:self.searchBar];
    self.searchBar.delegate = self;
    [_searchBar release];
    [_tableView release];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"回收键盘" style:UIBarButtonItemStylePlain target:self action:@selector(backClick:)];
   

    
//    
//    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height)];
//    [self.view addSubview:self.myView];
//    [_myView release];



}

- (void)backClick:(UIBarButtonItem *)button
{
    [self.searchBar resignFirstResponder];
}



//点击键盘搜索开始搜索
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self urlData];
    [searchBar resignFirstResponder];
}

- (void)dismissKeyboard:(id)sender
{
    [self.back resignFirstResponder];
}

//网络请求
-(void)urlData
{
    if ([AVSingleton shareSingleton].internetNum == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您现在没有网络,请检查网络!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    } else {
    NSString *str = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@&page=1&size=50&app=ttpod&v=v7.7.0.2015012818&uid=&mid=iPhone4&f=f320&s=s310&imsi=&hid=&splus=7.1.1&active=1&net=2&openudid=ad6f50f586818c4f36ff4358053c1b53fee58cdf&idfa=E2EAC64B-1F1C-4AC5-A0E1-8BE37A03FB96&utdid=VTCyBQSkYzwDAALO9zZTFfPC&alf=201200",self.searchBar.text];
    NSString *strEcode = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strEcode];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSMutableArray *dataArr = [dic objectForKey:@"data"];
        self.arr = [NSMutableArray array];
        
        for (NSMutableDictionary *dataDic in dataArr) {
            SearchModel *singer = [[SearchModel alloc] init];
            [singer setValuesForKeysWithDictionary:dataDic];
            NSMutableArray *urlArr = dataDic[@"url_list"];
            NSMutableDictionary *urlDic = [urlArr firstObject];
            [singer setValuesForKeysWithDictionary:urlDic];
             [self.arr addObject:singer];
            [singer release];
        }
        [self.tableView reloadData];
    }];
    }
}

//上拉加载
-(void)downAddData
{
    if ([AVSingleton shareSingleton].internetNum == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您现在没有网络,请检查网络!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    } else {
    static int page = 1;
    page++;
    NSString *str = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@&page=%d&size=50&app=ttpod&v=v7.7.0.2015012818&uid=&mid=iPhone4&f=f320&s=s310&imsi=&hid=&splus=7.1.1&active=1&net=2&openudid=ad6f50f586818c4f36ff4358053c1b53fee58cdf&idfa=E2EAC64B-1F1C-4AC5-A0E1-8BE37A03FB96&utdid=VTCyBQSkYzwDAALO9zZTFfPC&alf=201200",self.searchBar.text,page];
    NSString *strEcode = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strEcode];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSMutableArray *dataArr = [dic objectForKey:@"data"];
        for (NSMutableDictionary *dataDic in dataArr) {
            SearchModel *singer = [[SearchModel alloc] init];
            [singer setValuesForKeysWithDictionary:dataDic];
            [self.arr addObject:singer];
            [singer release];

        }
        [self.tableView reloadData];
    }];
        [self.tableView footerEndRefreshing];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.arr.count > 0) {
        [self.tableView addFooterWithCallback:^{
            [self downAddData];
        }];
        self.myView.hidden = YES;
    }
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[SearchCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:str] autorelease];
    }
    SearchModel *singer = self.arr[indexPath.row];
    cell.nameLabel.text = singer.song_name;
    cell.singerLabel.text = singer.singer_name;
    return cell;
}

//使用单例播放音乐
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    SearchModel *sear = self.arr[indexPath.row];
    if ([AVSingleton shareSingleton].fromNum != indexPath.row || [AVSingleton shareSingleton].fromNum != 0) {
        [[AFSoundManager sharedManager] stop];
    }
    NSLog(@"%@",sear.url);
    [[AFSoundManager sharedManager] startStreamingRemoteAudioFromURL:sear.url andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        [AVSingleton shareSingleton].percentage = percentage;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"mm:ss"];
        NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
        [AVSingleton shareSingleton].beginTime = [formatter stringFromDate:elapsedTimeDate];
        
        NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
        [AVSingleton shareSingleton].time = [formatter stringFromDate:timeRemainingDate];
        
        
    }];

    
    self.baseArr = [NSMutableArray array];
    
    for (NSInteger i = 0; i < self.arr.count; i++) {
        SearchModel *search = self.arr[i];
        BassModel *base = [[BassModel alloc] init];
        base.name1 = search.song_name;
        base.singerName1 = search.singer_name;
        [self.baseArr addObject:base];
        [base release];
    }
    [AVSingleton shareSingleton].fromArr = self.baseArr;
    [AVSingleton shareSingleton].fromNum = indexPath.row;
    [AVSingleton shareSingleton].myBool = YES;
    bofangViewController *play = [[bofangViewController alloc] init];
    [self presentViewController:play animated:YES completion:^{
        
    }];
    [play release];
    
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
